package com.sangeng.service.impl;
import ch.qos.logback.core.encoder.EchoEncoder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangeng.constants.SystemConstants;
import com.sangeng.domain.ResponseResult;
import com.sangeng.domain.dto.UserAddDto;
import com.sangeng.domain.dto.UserUpdateDto;
import com.sangeng.domain.entity.Role;
import com.sangeng.domain.entity.User;
import com.sangeng.domain.entity.UserRole;
import com.sangeng.domain.vo.PageVo;
import com.sangeng.domain.vo.UserInfoVo;
import com.sangeng.domain.vo.UserUpdateVo;
import com.sangeng.enums.AppHttpCodeEnum;
import com.sangeng.exception.SystemException;
import com.sangeng.mapper.UserMapper;
import com.sangeng.service.RoleService;
import com.sangeng.service.UserRoleService;
import com.sangeng.service.UserService;
import com.sangeng.utils.BeanCopyUtils;
import com.sangeng.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2023-10-03 15:34:53
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 根据用户id获取个人信息
     * @return
     */
    @Override
    public ResponseResult userInfo() {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id获取个人信息
        User user = getById(userId);
        //进行属性拷贝
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        return ResponseResult.okResult(userInfoVo);
    }
    /**
     * 修改个人信息并保存
     * @param user
     * @return
     */
    @Override
    public ResponseResult updateUserInfo(User user) {
        //根据用户id更新用户信息
        updateById(user);
        return ResponseResult.okResult();
    }
    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public ResponseResult register(User user) {
        //对数据进行非空判断
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if(userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        //...
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        //存入数据库
        save(user);
        return ResponseResult.okResult();
    }


    //判断昵称是否存在
    private boolean nickNameExist(String nickName) {
        LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
        lqw.eq(User::getUserName,nickName);
        return count(lqw)>0;
    }
    //判断用户名是否存在
    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
        lqw.eq(User::getUserName,userName);
        return count(lqw)>0;
    }
    /**
     * 分页查询所有的用户
     * 需要用户分页列表接口。可以根据用户名模糊搜索。
       可以进行手机号的搜索。可以进行状态的查询。
     * @param pageNum
     * @param pageSize
     * @param userName
     * @param phonenumber
     * @param status
     * @return
     */
    @Override
    public ResponseResult<PageVo> getAllUser(Integer pageNum, Integer pageSize,
                                             String userName, String phonenumber, String status) {
        LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
        lqw.like(StringUtils.hasText(userName),User::getUserName,userName);
        lqw.eq(StringUtils.hasText(phonenumber),User::getPhonenumber,phonenumber);
        lqw.eq(StringUtils.hasText(status), User::getStatus,status);
        Page<User> page=new Page<>(pageNum,pageSize);
        page(page,lqw);

        return ResponseResult.okResult(new PageVo(page.getRecords(),page.getTotal()));
    }
    /**
     * 添加用户
     需要新增用户功能。新增用户时可以直接关联角色。
    	注意：新增用户时注意密码加密存储。
     	用户名不能为空，否则提示：必需填写用户名
     	用户名必须之前未存在，否则提示：用户名已存在
       手机号必须之前未存在，否则提示：手机号已存在
       邮箱必须之前未存在，否则提示：邮箱已存在
     * @param userAddDto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult saveData(UserAddDto userAddDto) {
        //判断用户名是否为空
        if(!StringUtils.hasText(userAddDto.getUserName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
       //判断用户名是否存在
        LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
        lqw.eq(User::getUserName,userAddDto.getUserName());
        List<User> userList = list(lqw);
        if(null!=userList&&userList.size()>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.USERNAME_EXIST);
        }
        //判断手机号是否存在
        LambdaQueryWrapper<User> lqw2=new LambdaQueryWrapper<>();
        lqw2.eq(User::getPhonenumber,userAddDto.getPhonenumber());
        List<User> userList2 = list(lqw2);
        if(null!=userList2&&userList2.size()>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }

        //判断邮箱是否存在
        LambdaQueryWrapper<User> lqw3=new LambdaQueryWrapper<>();
        lqw3.eq(User::getEmail,userAddDto.getEmail());
        List<User> userList3 = list(lqw3);
        if(null!=userList3&&userList3.size()>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.EMAIL_EXIST);
        }
        //先在用户表添加用户
        User user = BeanCopyUtils.copyBean(userAddDto, User.class);
        //密码密文存储
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        save(user);
        //再在用户角色表中批量插入数据
        List<Long> roleIds = userAddDto.getRoleIds();
        List<UserRole> userRoleList = roleIds.stream().map(roleId -> new UserRole(user.getId(), roleId))
                .collect(Collectors.toList());

        userRoleService.saveBatch(userRoleList);
        return ResponseResult.okResult();
    }
    /**
     * 根据用户id删除用户，但是不能删除此时正在操作界面的用户
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteUserById(Long id) {
        //获取当前操作界面的用户是否和要删除的用户id相同
        if(SecurityUtils.getUserId().equals(id)){
            //抛出异常
            return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_USER_FAILED);
        }
        //删除用户
        removeById(id);
        //删除用户角色表中的记录
        LambdaQueryWrapper<UserRole> lqw=new LambdaQueryWrapper<>();
        lqw.eq(UserRole::getUserId,id);
        userRoleService.remove(lqw);
        return ResponseResult.okResult();
    }
    /**
     * 根据用户id查询用户信息，所有角色列表以及用户所选的角色id列表
     * @param id
     * @return
     */
    @Override
    public ResponseResult<UserUpdateVo> getUserById(Long id) {
        //获取用户信息
        User user = getById(id);
        //获取所有角色列表(状态正常）
        LambdaQueryWrapper<Role> lqw=new LambdaQueryWrapper();
        lqw.eq(Role::getStatus, SystemConstants.ROLE_STATUS_NORMAL);
        List<Role> roleList = roleService.list(lqw);
        //获取用户所选的角色id列表
        LambdaQueryWrapper<UserRole> lqw2=new LambdaQueryWrapper<>();
        lqw2.eq(UserRole::getUserId,id);
        List<UserRole> userRoleList = userRoleService.list(lqw2);
        List<Long> roleIds= userRoleList.stream().map(userRole -> userRole.getRoleId())
                .collect(Collectors.toList());
        return ResponseResult.okResult(new UserUpdateVo(roleIds,roleList,user));
    }
    /**
     * 更新用户信息，用户角色表也要更新
     * @param userUpdateDto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult updateUser(UserUpdateDto userUpdateDto) {
        User user = BeanCopyUtils.copyBean(userUpdateDto, User.class);
        updateById(user);
        //先删除用户所具有的角色
        LambdaQueryWrapper<UserRole> lqw=new LambdaQueryWrapper<>();
        lqw.eq(UserRole::getUserId,user.getId());
        userRoleService.remove(lqw);
        //再添加修改的用户的角色
        List<Long> roleIds = userUpdateDto.getRoleIds();
        List<UserRole> userRoleList = roleIds.stream().map(roleId -> new UserRole(user.getId(), roleId))
                .collect(Collectors.toList());
        userRoleService.saveBatch(userRoleList);
        return ResponseResult.okResult();
    }


}
